package com.sbj.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.zhxu.bs.BeanSearcher;
import cn.zhxu.bs.operator.Equal;
import cn.zhxu.bs.util.MapUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sbj.dto.config.KdConfiguration;
import com.sbj.dto.kdn.model.KdnApiModel;
import com.sbj.dto.res.OrderItemRes;
import com.sbj.dto.res.OrderKdRes;
import com.sbj.entity.Order;
import com.sbj.entity.OrderKd;
import com.sbj.mapper.OrderKdMapper;
import com.sbj.service.OrderKdService;
import com.sbj.service.OrderService;
import com.zmh.framework.exception.ResultException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author summer
 * @version 1.0
 * @date 2024/9/14 16:50
 */
@Service
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
public class OrderKdServiceImpl extends ServiceImpl<OrderKdMapper, OrderKd> implements OrderKdService {

    private final BeanSearcher beanSearcher;

    private static final String  SF="SF";

    private final KdConfiguration kdConfiguration;

    @Override
    public Map<String,Object> kdInfo(Integer orderId) {
        OrderService orderService = SpringUtil.getBean(OrderService.class);
        OrderItemRes orderItem = orderService.findOrderItem(orderId);
        if(ObjectUtil.isNull(orderItem)){
            throw new ResultException("订单不存在");
        }
        Map<String, Object> build = MapUtils.builder().field(OrderKdRes::getOrderId, orderId).op(Equal.class).build();
        OrderKdRes orderKdRes = beanSearcher.searchFirst(OrderKdRes.class, build);
        KdnApiModel kdnApiModel = new KdnApiModel();
        kdnApiModel.setShipperCode(orderKdRes.getCode());
        kdnApiModel.setLogisticCode(orderKdRes.getKdCode());
        if(orderKdRes.getCode().equals(SF)){
            CharSequence charSequence = PhoneUtil.subAfter(orderItem.getPhone());
            kdnApiModel.setCustomerName(charSequence.toString());
        }
        String s = kdConfiguration.sendKdInfo(kdnApiModel);
        Map<String, Object> map = Convert.convert(new TypeReference<Map<String, Object>>() {
        }, JSON.parseObject(s));
        return map;
    }
}
